package org.example.quickstart;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        // 1.获取连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.56.108");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();

        // 3.通过connection创建Channel
        Channel channel = connection.createChannel();

        // 4. 声明（创建）一个队列
        /**
         * 参数：queue:队列名称
         * durable: 为true,声明一个持久化队列
         * exclusive：为true，声明一个排他队列（此连接独占）
         * autoDelete： 为true，声明一个自动删除队列，服务器将在不再使用它时将其删除
         */
        channel.queueDeclare("test001",true,false,false,null);

        // 5.创建消费者
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(consumerTag);
                System.out.println(envelope.toString());
                System.out.println(properties.toString());
                System.out.println("消息内容:" + new String(body));
            }
        };
        // 6.设置通道
        channel.basicConsume("test001", true, defaultConsumer );

    }
}
